<?php

namespace App\Http\Controllers\platform;

use App\Http\Controllers\Controller;
use App\Models\Reviews;
use Illuminate\Http\Request;

class CommonController extends Controller
{
    public function index(Request $Request)
    {
        if(!$Request->id){
            return response()->json(['code' => '403', 'msg' => '参数错误']);
        }
        $data = Reviews::where('product_id',$Request->id)->where('status',1)->with('user')->orderBy('id','desc')->get();
        foreach ($data as $key => $value) {
            $data[$key]->user_name = '学习用户';
            $data[$key]->delete = false;
            if($value->user){
                $data[$key]->user_name = $value->anonymous == 1 ? '匿名用户' : $value->user->name;
            }
            if($Request->uid == $value->uid){
                $data[$key]->delete = true;
            }
            
        }
        return response()->json(['code' => '200', 'msg' => 'success','data'=>$data]);
    }

    public function store(Request $Request)
    {
        if(!$Request->content){
            return response()->json(['code' => '403', 'msg' => '请输入评论内容']);
        }
        if(!$Request->product_id){
            return response()->json(['code' => '403', 'msg' => '请输入选择要评论的课程']);
        }
        $data = new Reviews();
        $data->content = $Request->content;
        $data->uid = $Request->uid;
        $data->product_id = $Request->product_id;
        $data->course_type = 'ec';
        $data->anonymous = $Request->anonymous ?? 0;
        $data->create_time = time();
        $data->update_time = time();
        $data->stars = 0;
        $data->name = '';
        $data->tell = '';
        $data->type = 1;
        $data->status = 1;
        $data->save();
        return response()->json(['code' => '200', 'msg' => 'success','data'=>$data]);
    }

    public function delete(Request $Request)
    {
        if(!$Request->id){
            return response()->json(['code' => '403', 'msg' => '请选择评论']);
        }
        $data = Reviews::where('uid',$Request->uid)->where('id',$Request->id)->first();
        $data->delete();
        return response()->json(['code' => '200', 'msg' => '删除成功','data'=>$data]);
    }
}
